package com.atcc.test.util;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {

	@Autowired
	private RedisTemplate<String,Object> redisTemplate;
	
	/**
	 * 判断key值是否存在
	 * @param key
	 * @return 
	 */
	public boolean hasKey(String key) {
		try {
			return redisTemplate.hasKey(key);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 设置key的过期时间
	 * @param key
	 * @param time
	 * @return
	 */
	public boolean expire(String key,long time) {
		try {
			return redisTemplate.expire(key, time, TimeUnit.SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 获取key值的过期时间
	 * @param key
	 * @return
	 */
	public long getExpire(String key) {
		try {
			if(hasKey(key)) return redisTemplate.getExpire(key,TimeUnit.SECONDS);
			else return -1L;
		} catch (Exception e) {
			e.printStackTrace();
			return -2L;
		}
	}
	
	/**
	 * 获取普通缓存
	 * @param key
	 * @return
	 */
    public Object get(String key) {
		return key == null?null:redisTemplate.opsForValue().get(key);
    }
    
    /**
     * 设置普通缓存
     * @param key
     * @param object
     * @return
     */
    public boolean set(String key,Object object) {
    	try {
			redisTemplate.opsForValue().set(key, object);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
    }
	
    /**
     * 设置key值递增
     * @param key
     * @param delta
     * @return
     */
    public long incr(String key,long delta) {
        if(delta<0) throw new RuntimeException("递增参数设置错误");
        else return redisTemplate.opsForValue().increment(key, delta);
    }
    
    /**
     * 设置key值递减
     * @param key
     * @param delta
     * @return
     */
    public long decr(String key,long delta) {
    	if(delta>0) throw new RuntimeException("递减参数设置错误");
    	else return redisTemplate.opsForValue().decrement(key, delta);
    }
    

}

